<template>
  <view class="contract-container">
    <!-- 顶部导航 -->
    <view class="nav-header">
      <view class="nav-back" @click="goBack">
        <text class="back-icon">‹</text>
      </view>
      <text class="nav-title">创建合同</text>
      <view class="nav-placeholder"></view>
    </view>
    <view class="content-wrapper">
      <view class="main-content">
        <view class="contract-title">
          <text class="title-text">补合同</text>
        </view>
        <view class="form-container">
          <view class="warp-card" v-if="formData.borrowerType == 'lender'">
            <!-- 出借人信息 -->
            <view class="form-item">
              <text class="label">出借人</text>
              <view class="input-wrapper">
                <text>{{ setLenderName('lender') }}</text>
              </view>
            </view>

            <!-- 借款人信息 -->
            <view class="form-item clickable" @click="selectBorrower">
              <text class="label">借款人</text>
              <view class="input-wrapper">
                <view
                >
                {{ formData.contractType }}
                </view>
                <text class="arrow">›</text>
              </view>
            </view>

            <!-- 姓名 -->
            <view class="form-item" v-if="formData.contractType === '由我填写'">
              <text class="label required">借款人姓名</text>
              <view class="input-wrapper">
                <input
                  class="form-input"
                  v-model="formData.borrowerRealName"
                  placeholder="请输入真姓名"
                />
              </view>
            </view>

            <!-- 身份证号码 -->
            <view class="form-item" v-if="formData.contractType === '由我填写'">
              <text class="label required">借款人身份证号码</text>
              <view class="input-wrapper">
                <input
                  class="form-input"
                  v-model="formData.borrowerRealIdCard"
                  placeholder="请输入真身份证号码"
                />
              </view>
            </view>
          </view>

           <view class="warp-card" v-if="formData.borrowerType == 'borrower'">
            <!-- 出借人信息 -->
            <view class="form-item">
              <text class="label">借款人</text>
              <view class="input-wrapper">
                <text>{{ setLenderName('borrower') }}</text>
              </view>
            </view>

            <!-- 借款人信息 -->
            <view class="form-item clickable" @click="selectBorrower">
              <text class="label">借款人</text>
              <view class="input-wrapper">
                <view
                >
                {{ formData.contractType }}
                </view>
                <text class="arrow">›</text>
              </view>
            </view>

            <!-- 姓名 -->
            <view class="form-item" v-if="formData.contractType === '由我填写'">
              <text class="label required">出借人姓名</text>
              <view class="input-wrapper">
                <input
                  class="form-input"
                  v-model="formData.lenderRealName"
                  placeholder="请输入真姓名"
                />
              </view>
            </view>

            <!-- 身份证号码 -->
            <view class="form-item" v-if="formData.contractType === '由我填写'">
              <text class="label required">出借人身份证号码</text>
              <view class="input-wrapper">
                <input
                  class="form-input"
                  v-model="formData.lenderRealCardId"
                  placeholder="请输入真身份证号码"
                />
              </view>
            </view>
          </view>


          <view class="warp-card">
            <!-- 合同金额 -->
            <view class="form-item">
              <text class="label required">合同金额</text>
              <view class="input-wrapper">
                <input
                  class="form-input"
                  v-model="formData.contractAmount"
                  placeholder="合同金额"
                  type="digit"
                />
              </view>
            </view>

            <!-- 大写金额 -->
            <view class="form-item">
              <text class="label">大写金额</text>
              <view class="input-wrapper">
                <input
                  class="form-input"
                  v-model="formData.amountInWords"
                  placeholder="大写金额"
                  disabled
                />
              </view>
            </view>

            <!-- 还款方式 -->
            <view class="form-item clickable" @click="selectRepaymentMethod">
              <text class="label">还款方式</text>
              <view class="input-wrapper">
                <text>{{ formData.repaymentMethod }}</text>
                <text class="arrow"> ›</text>
              </view>
            </view>

            <!-- 起始日期 -->
            <view class="form-item clickable">
              <text class="label required">起始日期</text>
              <view class="input-wrapper">
                <picker
                  mode="date"
                  :value="formData.startDate"
                  @change="onStartDateChange"
                  :start="startDate"
                  :end="endDate"
                >
                  <view class="uni-input" v-if="formData.startDate">{{
                    formData.startDate
                  }}</view>
                  <view v-else class="uni-input-tips"> 点击选择时间 </view>
                </picker>
                <text class="arrow">›</text>
              </view>
            </view>

            <!-- 还款日期 -->
            <view class="form-item clickable">
              <text class="label required">还款日期</text>
              <view class="input-wrapper">
                <picker
                  mode="date"
                  :value="formData.endDate"
                  @change="onEndDateChange"
                  :start="formData.startDate || startDate"
                  :end="endDate"
                >
                  <view class="uni-input" v-if="formData.endDate">{{
                    formData.endDate
                  }}</view>
                  <view v-else class="uni-input-tips"> 点击选择时间 </view>
                </picker>
                <text class="arrow">›</text>
              </view>
            </view>

            <!-- 借款天数 -->
            <view class="form-item">
              <text class="label">借款天数</text>
              <view class="input-wrapper">
                <input
                  class="form-input"
                  v-model="formData.loanDays"
                  placeholder="自动计算"
                  disabled
                />
              </view>
            </view>

            <!-- 年化利率 -->
            <view class="form-item">
              <text class="label">年化利率</text>
              <view class="input-wrapper rate-wrapper">
                <input
                  class="form-input rate-input"
                  v-model="formData.annualRate"
                  placeholder="0"
                  type="digit"
                />
                <text class="rate-unit">%</text>
                <view class="rate-info" @click="showRateInfo">
                  <text class="info-icon">ⓘ</text>
                </view>
              </view>
            </view>
          </view>
          <view class="warp-card">
            <!-- 合同原因 -->
            <view class="form-item clickable" @click="selectContractReason">
              <text class="label">合同原因</text>
              <view class="input-wrapper">
                <text>{{ formData.contractReason }}</text>
                <text class="arrow">›</text>
              </view>
            </view>

            <!-- 补充说明 -->
            <view class="form-item textarea-item">
              <text class="label">补充说明（选填）</text>
              <view class="textarea-wrapper">
                <textarea
                  class="form-textarea"
                  v-model="formData.additionalNotes"
                  placeholder="以下内容将在对方确认时同步显示，对方确认后将成为合同内容"
                  maxlength="500"
                ></textarea>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部按钮 -->
    <view class="bottom-actions"  >
      <button
        class="submit-btn"
        @click="submitContract"
      >
        提交
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, watch } from "vue";
import request from "@/api/request.js";
import { onLoad,onShow } from "@dcloudio/uni-app";

// 表单数据
const formData = ref({
  lenderName: "",
  lenderIdCard: "",
  contractType: "由我填写",
  borrowerType: 'lender',
  borrowerRealName: "",
  borrowerRealIdCard: "",
  contractAmount: "",
  amountInWords: "",
  repaymentMethod: "一次性还本付息",
  startDate: "",
  endDate: "",
  loanDays: "",
  annualRate: "0",
  contractReason: "周转",
  additionalNotes: "",
});

// 日期选择器相关状态
const startDate = "2020-01-01";
const endDate = "2030-12-31";

onLoad((option)=>{
  formData.value.borrowerType = option.borrowerType
}) 
onShow(()=>{
// 组件挂载时加载用户信息
  loadUserInfo();
})

// 加载用户信息
const loadUserInfo = () => {
  const savedUserInfo = uni.getStorageSync("userInfo");
  console.log(savedUserInfo,formData.value.borrowerType,'...')
  if (savedUserInfo) {
    if (formData.value.borrowerType === 'lender') {
      formData.value.lenderName = savedUserInfo.realName;
      formData.value.lenderIdCard = savedUserInfo.idCard;
     
    } else {
         formData.value.borrowerRealName = savedUserInfo.realName;
      formData.value.borrowerRealIdCard = savedUserInfo.idCard;
    }
  }
};
const setLenderName = (type) => {
  let text = "";
  if (type === 'lender') {
    text = formData.value.lenderName;
  } else {
    text = formData.value.borrowerRealName;
  }
  if (type === 'lender') {
    if (formData.value.lenderIdCard) {
      // 只显示前四位和后四位，中间*显示
      text +=
        " " +
        formData.value.lenderIdCard.slice(0, 4) +
        "********" +
        formData.value.lenderIdCard.slice(-4);
    }
  } else {
    if (formData.value.borrowerRealIdCard) {
      // 只显示前四位和后四位，中间*显示
      text +=
        " " +
        formData.value.borrowerRealIdCard.slice(0, 4) +
        "********" +
        formData.value.borrowerRealIdCard.slice(-4);
    }
  }
  return text;
};

// 表单验证
const isFormValid = computed(() => {
  // 只有“由我填写”时才校验姓名和身份证
  const isBorrowerSelf = formData.value.borrowerRealName === "由我填写";
  return (
    (!isBorrowerSelf ||
      (formData.value.borrowerRealName && formData.value.borrowerRealIdCard)) &&
    formData.value.contractAmount &&
    formData.value.startDate &&
    formData.value.endDate
  );
});

// 监听合同金额变化，自动转换大写
watch(
  () => formData.value.contractAmount,
  (newVal) => {
    if (newVal) {
      formData.value.amountInWords = convertToChineseNumber(newVal);
    } else {
      formData.value.amountInWords = "";
    }
  }
);

// 监听日期变化，自动计算借款天数
watch(
  [() => formData.value.startDate, () => formData.value.endDate],
  ([start, end]) => {
    if (start && end) {
      const startTime = new Date(start).getTime();
      const endTime = new Date(end).getTime();
      const days = Math.ceil((endTime - startTime) / (1000 * 60 * 60 * 24));
      formData.value.loanDays = days > 0 ? days.toString() : "";
    } else {
      formData.value.loanDays = "";
    }
  }
);

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 选择借款人
const selectBorrower = () => {
  uni.showActionSheet({
    itemList: ["发送给ta后由ta填写", "由我填写"],
    success: (res) => {
      if (res.tapIndex === 0) {
        // 隐藏姓名和身份证
        formData.value.contractType = "发送给ta后由ta填写";
        if(formData.value.borrowerType === 'lender'){
          formData.value.borrowerRealName = "";
          formData.value.borrowerRealIdCard = "";
        }
        if(formData.value.borrowerType === 'borrower'){
          formData.value.lenderRealName = "";
          formData.value.lenderRealCardId = "";
        }
      } else {
        // 显示姓名和身份证
        formData.value.contractType = "由我填写";
      }
      console.log(formData.value,'...')
    },
  });
};

// 选择还款方式
const selectRepaymentMethod = () => {
  uni.showActionSheet({
    itemList: ["一次性还本付息", "按月付息到期还本", "等额本息", "等额本金"],
    success: (res) => {
      const methods = [
        "一次性还本付息",
        "按月付息到期还本",
        "等额本息",
        "等额本金",
      ];
      formData.value.repaymentMethod = methods[res.tapIndex];
    },
  });
};

// 选择合同原因
const selectContractReason = () => {
  uni.showActionSheet({
    itemList: ["周转", "投资", "消费", "其他"],
    success: (res) => {
      const reasons = ["周转", "投资", "消费", "其他"];
      formData.value.contractReason = reasons[res.tapIndex];
    },
  });
};
// 起始日期选择
const onStartDateChange = (e) => {
  formData.value.startDate = e.detail.value;
  // 如果还款日期早于起始日期，自动清空还款日期
  if (
    formData.value.endDate &&
    formData.value.endDate < formData.value.startDate
  ) {
    formData.value.endDate = "";
  }
};

// 还款日期选择
const onEndDateChange = (e) => {
  // 如果还款日期早于起始日期，提示用户
  if (formData.value.startDate && e.detail.value <= formData.value.startDate) {
    uni.showToast({
      title: "还款日期不能早于等于起始日期",
      icon: "none",
    });
    return;
  }
  formData.value.endDate = e.detail.value;
};
// 显示利率说明
const showRateInfo = () => {
  uni.showModal({
    title: "年化利率说明",
    content:
      "年化利率是指一年的存款利率。请根据实际情况填写，建议不超过法定利率上限。",
    showCancel: false,
  });
};

// 提交合同
const submitContract = async () => {
  if (!isFormValid.value) {
    uni.showToast({
      title: "请完善必填信息",
      icon: "none",
    });
    return;
  }

  try {
    console.log(formData.value);
    // 调用API提交合同数据
    request
      .post("/api/contracts/generate", {
        ...formData.value,
      })
      .then((res) => {
        if (res.code === 200) {
          uni.showToast({
            title: "合同创建成功",
            icon: "success",
          });
          uni.navigateTo({
            url: `/pages/borrow/contractPreview?contractNumber=${res.data.contractNumber}`,
          });
        }
      });
  } catch (error) {
    uni.showToast({
      title: error.message || "提交失败，请重试",
      icon: "none",
    });
  }
};

// 数字转中文大写
const convertToChineseNumber = (num) => {
  const digits = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"];
  const units = ["", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿"];

  if (!num || isNaN(num)) return "";

  const numStr = Math.floor(parseFloat(num)).toString();
  let result = "";

  for (let i = 0; i < numStr.length; i++) {
    const digit = parseInt(numStr[i]);
    const unit = units[numStr.length - 1 - i];

    if (digit !== 0) {
      result += digits[digit] + unit;
    } else if (result && !result.endsWith("零")) {
      result += "零";
    }
  }

  return result + "元整";
};


</script>

<style scoped>
.contract-container {
  min-height: 100vh;
  background: #f5f6fa;
}

/* 顶部导航 */
.nav-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  padding-top: calc(var(--status-bar-height) + 20rpx);
  background: #ffffff;
  border-bottom: 1rpx solid #eee;
  position: sticky;
  top: 0;
  z-index: 100;
}

.nav-back {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: #f8f9fa;
}

.back-icon {
  font-size: 36rpx;
  color: #333;
  font-weight: bold;
}

.nav-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.nav-placeholder {
  width: 60rpx;
}

/* 内容包装器 */
.content-wrapper {
  min-height: calc(100vh - 120rpx);
  overflow-y: auto;
}

/* 主要内容 */
.main-content {
  padding-bottom: 120rpx;
}

/* 合同标题 */
.contract-title {
  padding: 40rpx 30rpx 20rpx;
  background: #ffffff;
  margin-bottom: 20rpx;
}

.title-text {
  font-size: 40rpx;
  font-weight: bold;
  color: #333;
}

/* 表单容器 */
.form-container {
  padding: 0 30rpx;
}

/* 表单项 */
.form-item {
  padding: 30rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.form-item:last-child {
  border-bottom: none;
}

.label {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  min-width: 200rpx;
  margin-right: 20rpx;
  margin-bottom: 0;
}

.label.required::after {
  content: "*";
  color: #ff4757;
  margin-left: 4rpx;
}

.input-wrapper {
  display: flex;
  align-items: center;
  position: relative;
  flex: 1;
  justify-content: flex-end;
}

.form-input {
  font-size: 28rpx;
  color: #333;
  background: transparent;
  border: none;
  outline: none;
  text-align: right;
  width: 100%;
}

.form-input::placeholder {
  color: #999;
}

.form-input:disabled {
  color: #666;
}

.amount-input {
  font-size: 32rpx;
  font-weight: bold;
  color: #ff6b35;
}

.arrow {
  font-size: 32rpx;
  color: #ccc;
  margin-left: 20rpx;
}

.clickable {
  cursor: pointer;
}

.clickable:active {
  background: #f8f9fa;
}

/* 利率输入 */
.rate-wrapper {
  display: flex;
  align-items: center;
}

.rate-input {
  flex: 1;
  text-align: right;
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.rate-unit {
  font-size: 28rpx;
  color: #333;
  margin-left: 8rpx;
  margin-right: 20rpx;
}

.rate-info {
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: #f0f0f0;
}

.info-icon {
  font-size: 24rpx;
  color: #666;
}
.warp-card {
  margin-bottom: 40rpx;
  background: #ffffff;
  padding: 30rpx;
  border-radius: 12rpx;
}
/* 文本域 */
.textarea-item {
  padding-bottom: 40rpx;
  flex-direction: column;
  align-items: flex-start;
}

.textarea-item .label {
  margin-bottom: 20rpx;
  min-width: auto;
}

.textarea-item .input-wrapper {
  width: 100%;
  justify-content: stretch;
}

.textarea-wrapper {
  background: #f8f9fa;
  border-radius: 12rpx;
  padding: 20rpx;
  width: 100%;
  box-sizing: border-box;
}

.form-textarea {
  width: 100%;
  min-height: 200rpx;
  font-size: 28rpx;
  color: #333;
  background: transparent;
  border: none;
  outline: none;
  resize: none;
  line-height: 1.6;
}

.form-textarea::placeholder {
  color: #999;
  line-height: 1.6;
}

/* 底部按钮 */
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 30rpx;
  background: #ffffff;
  border-top: 1rpx solid #eee;
  z-index: 100;
  transition: opacity 0.3s ease;
}

/* 当显示日期选择器时隐藏底部按钮 */
.bottom-actions.hidden {
  opacity: 0;
  pointer-events: none;
}

.submit-btn {
  width: 100%;
  height: 88rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #ffffff;
  font-size: 32rpx;
  font-weight: bold;
  border: none;
  border-radius: 44rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

/* 或者完全隐藏 */
.bottom-actions.hidden {
  display: none;
}

.submit-btn:disabled {
  background: #ccc;
  color: #999;
}

.submit-btn:not(:disabled):active {
  transform: scale(0.98);
  opacity: 0.9;
}
/* 日期选择器样式 */
.date-picker-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 9999;
  display: flex;
  align-items: flex-end;
}

.date-picker-container {
  width: 100%;
  background: #ffffff;
  border-radius: 20rpx 20rpx 0 0;
  overflow: hidden;
}

.date-picker-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.date-picker-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.date-picker-actions {
  display: flex;
  gap: 40rpx;
}

.date-picker-cancel {
  font-size: 28rpx;
  color: #999;
}

.date-picker-confirm {
  font-size: 28rpx;
  color: #667eea;
  font-weight: bold;
}

.date-picker-view {
  height: 400rpx;
}

.picker-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 80rpx;
  font-size: 28rpx;
  color: #333;
}

/* 日期选择器样式 */
.date-picker-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.picker-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
}

.date-picker-content {
  position: relative;
  background: white;
  border-radius: 16rpx;
  width: 600rpx;
  max-width: 90vw;
  padding: 40rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
}

.date-picker-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40rpx;
}

.date-picker-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.date-picker-close {
  font-size: 48rpx;
  color: #999;
  cursor: pointer;
  line-height: 1;
}

.date-input {
  width: 100%;
  height: 80rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  margin-bottom: 40rpx;
  box-sizing: border-box;
}
.uni-input-tips {
  font-size: 28rpx;
  color: #999;
}
.date-picker-actions {
  display: flex;
  gap: 20rpx;
}

.date-picker-btn {
  flex: 1;
  height: 80rpx;
  border: none;
  border-radius: 8rpx;
  font-size: 28rpx;
  cursor: pointer;
}

.date-picker-btn.cancel {
  background: #f5f5f5;
  color: #666;
}

.date-picker-btn.confirm {
  background: #667eea;
  color: white;
}

/* 响应式设计 */
@media (max-width: 750rpx) {
  .form-item {
    padding: 24rpx 0;
  }

  .label {
    font-size: 26rpx;
    min-width: 160rpx;
    margin-right: 16rpx;
  }

  .form-input {
    font-size: 26rpx;
  }

  .amount-input {
    font-size: 28rpx;
  }

  .rate-input {
    width: 100rpx;
  }
}
</style>
